/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Modulo4;

import Acceso.Security;
import Modelo.*;
import Modelo.DAL.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 *
 * @author Dayana
 */
public class consultarRepososPermisosAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";

    boolean validarCedula(ActionErrors errors, String cadena, String err, HttpServletRequest request, Pattern p) {
        Matcher m;
        m = p.matcher(cadena);
        if (!m.matches()) {
            errors.add(err, new ActionMessage("errors.invalid_Cedula"));
            saveErrors(request, errors);
            return true;
        }
        return false;
    }

    boolean validarCaracteres(ActionErrors errors, String cadena, String err, HttpServletRequest request, Pattern p) {

        Matcher m;
        m = p.matcher(cadena);

        if (m.find()) {
            errors.add(err, new ActionMessage("errors." + err));
            saveErrors(request, errors);
            return true;
        }
        return false;
    }

    boolean validarUsbid(ActionErrors errors, String cadena, String err, HttpServletRequest request, Pattern p) {
        Matcher m;
        m = p.matcher(cadena);
        if (!m.matches()) {
            errors.add(err, new ActionMessage("errors.invalid_UsbId"));
            saveErrors(request, errors);
            return true;
        }
        return false;
    }

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        String[] a = {"Administrador","Director DSI","Jefe Apoyo Administrativo","Personal Administrativo","Supervisor","Vigilante"};
       if (!Security.validateSession(request, a)) {
            return mapping.findForward("errorPriv");
        }

        System.out.println("Paso Autenticación");

        agregarRepososPermisosForm formBean = (agregarRepososPermisosForm) form;
        ActionErrors errors = new ActionErrors();


        //Obtengo las cosas del formulario
        String voe = formBean.getVoe().trim();
        String ci = formBean.getCi().trim();
        String usbid = formBean.getUsbid();
        String nombre1 = formBean.getNombre1();
        String apellido1 = formBean.getApellido1();
        boolean hayError = false;
        boolean momento;
        Pattern p;
        Matcher m;
        ComunidadUniversitaria personaCU = new ComunidadUniversitaria();
        PersonalUsb PUSB = new PersonalUsb();
        Personal_DAO conexionPersonal = new Personal_DAO();
        String ci2 = null;


        //Comprueba que el campo cedula solo tenga numeros
        p = Pattern.compile("[0-9]*");
        momento = validarCedula(errors, ci, "invalid_Cedula", request, p);
        hayError = (momento || hayError);

        String CIcompuesta = voe + "-" + ci;

        if (usbid.length() > 1) {
            //Comprueba que el campo usbid solo tenga letras
            p = Pattern.compile("[a-zA-Z]+");
            momento = validarUsbid(errors, usbid, "invalid_UsbId", request, p);
            hayError = (momento || hayError);
        }

        // comprueba que el campo solo tenga caracteres a-z y espacios " "
        p = Pattern.compile("[^a-zA-Záéíóú ]+");
        momento = validarCaracteres(errors, nombre1, "invalid_caracter_N1", request, p);
        hayError = (momento || hayError);
        momento = validarCaracteres(errors, apellido1, "invalid_caracter_A1", request, p);
        hayError = (momento || hayError);


        if (!hayError) {

            if (ci.length() < 1) {
                if (nombre1.length() > 1 && apellido1.length() > 1) {
                    ci = Permisos_DAO.obtenerCedula(nombre1, apellido1);

                    if (ci == null) {
                        errors.add("nombre_apellido_invalido", new ActionMessage("errors.nombre_apellido_invalido"));
                        saveErrors(request, errors);
                        return mapping.findForward(FAILURE);
                    }
                    //    ci = ci.substring(0,2) + ci.substring(2, 10);
                } else if (usbid.length() > 1) {
                    ci = Permisos_DAO.obtenerCedula2(usbid);
                } else {
                    errors.add("especificarApellido", new ActionMessage("errors.especificarApellido"));
                    saveErrors(request, errors);
                    return mapping.findForward(FAILURE);
                }

            } else {
                ci = voe + "-" + ci;

                if (nombre1.length() > 1 && apellido1.length() > 1) {
                    ci2 = Permisos_DAO.obtenerCedula(nombre1, apellido1);

                    if (ci2 == null) {
                        errors.add("nombre_apellido_invalido", new ActionMessage("errors.nombre_apellido_invalido"));
                        saveErrors(request, errors);
                        //  return mapping.findForward(FAILURE);
                    } else { //este caso corresponde con cedula mal y nombre y apellido bien
                        if (!ci.equals(ci2)) {
                            ci = ci2;
                        }
                    }
                }
            }

            // Como no hay error procedo a llenar la lista con la consulta en el dao
            List<Permiso> data = Permisos_DAO.consultarPermisos(ci);

            System.out.println("ci: " + ci);
            if (data == null || data.size() < 1) {
                errors.add("No_hay_Resultados", new ActionMessage("errors.No_hay_Resultados"));
                saveErrors(request, errors);
                return mapping.findForward(FAILURE);
            }

            formBean.setPermisos(data);
            formBean.setVoe(voe);
            formBean.setCi(ci);
            formBean.setNombre1(nombre1);
            formBean.setApellido1(apellido1);




            return mapping.findForward(SUCCESS);

            //hay error
        } else {

            return mapping.findForward(FAILURE);
        }
    }
}
